const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
// 读取 package.json 文件
const packageJsonPath = path.join(process.cwd(), "package.json");
const packageJsonContent = fs.readFileSync(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonContent);

const { type } = getEnvParams(process.argv);
(async () => {
  const kingonDependencies = Object.keys(packageJson.dependencies || {}).filter((dep) => dep.startsWith("@kingon/"));
  const nodeBuildName = "node_build";
  if (kingonDependencies.length > 0) {
    if (type == "build") {
      // 判断是否有指定文件夹node_build
      if (!fs.existsSync(nodeBuildName)) {
        fs.mkdirSync(nodeBuildName);
      }
      // 打包以 @kingon/ 开头的依赖包
      kingonDependencies.forEach((dep) => {
        try {
          console.log(`Packing ${dep}...`);
          execSync(`npm pack ${dep} --pack-destination=./${nodeBuildName}`);
          console.log(`${dep} packed successfully.`);
        } catch (error) {
          console.error(`Error packing ${dep}:`, error.message);
        }
      });
    } else {
      if (!fs.existsSync(nodeBuildName)) {
        console.log(`${nodeBuildName} does not exist.`);
        return;
      }
      let installCommands = [];
      // 获取目录下面的文件
      const files = fs.readdirSync(nodeBuildName); // 使用同步方法获取文件
      files.forEach((file) => {
        if (file.endsWith(".tgz")) {
          installCommands.push(`npm install ./${nodeBuildName}/${file}`);
        }
      });
      const installCommand = installCommands.join(" && ");
      console.log("installCommands:", installCommand);
      try {
        execSync(installCommands.join(" && "));
      } catch (error) {
        console.error(`Error installCommands： ${installCommand}:`, error.message);
      }
    }
  } else {
    console.log("No @kingon/ dependencies found.");
  }
})();

/**
 * 获取node命令行参数
 * @param {array} options 命令行数组
 */
function getEnvParams(options) {
  let envParams = {};
  // 从第三个参数开始,是自定义参数
  for (let i = 2, len = options.length; i < len; i++) {
    let arg = options[i].split("=");
    envParams[arg[0]] = arg[1];
  }
  return envParams;
}